# coding=utf-8

from datetime import datetime
from django.contrib.auth.models import AbstractBaseUser, UserManager
from django.db import models
from django.utils import timezone
from raven.utils import json

BASE_DATE_FROMATE = '%Y-%m-%d'
BASE_DATETIME_FROMATE = '%Y-%m-%d %H:%M:%S'
BASE_TIME_FORMATE = '%H:%M'

class JSONBaseMixin(object):

    def toJSON(self):

        fields = []
        for field in self._meta.fields:
            fields.append((field.name, field.attname, type(field)))

        d = {}
        for attr, attname, t in fields:
            if getattr(self, attname) == None:
                if t == models.DateTimeField:
                    d[attr] = ''
                elif t == models.DateField:
                    d[attr] = ''
                elif t == models.TimeField:
                    d[attr] = ''
                elif t == models.CommaSeparatedIntegerField:
                    d[attr] = []
                elif t == models.CharField:
                    d[attr] = ''
                elif t == models.IntegerField:
                    d[attr] = 0
                elif t == models.AutoField:
                    d[attr] = 0
                elif t == models.OneToOneField:
                    d[attr] = 0
                elif t == models.ForeignKey:
                    d[attr] = 0
                elif t == models.EmailField:
                    d[attr] = ""
                elif t == models.URLField:
                    d[attr] = ""
                elif t == models.TextField:
                    d[attr] = ""
                elif t == models.BigIntegerField:
                    d[attr] = 0
                elif t == models.BooleanField:
                    d[attr] = False
                elif t == models.DecimalField:
                    d[attr] = 0
                elif t == models.FloatField:
                    d[attr] = 0.0
                elif t == models.NullBooleanField:
                    d[attr] = False
                else:
                    d[attr] = ""
            else:
                if t == models.DateTimeField and not isinstance(getattr(self, attname), (str, unicode)):

                    try:
                        d[attr] = getattr(self, attname).strftime(BASE_DATETIME_FROMATE)
                    except:
                        d[attr] = '2015-06-01 01:01:01'
                elif t == models.DateField and not isinstance(getattr(self, attname), (str, unicode)):
                    try:
                        d[attr] = getattr(self, attname).strftime(BASE_DATE_FROMATE)
                    except:
                        d[attr] = '2015-06-01'
                elif t == models.TimeField and not isinstance(getattr(self, attname), (str, unicode)):
                    try:
                        d[attr] = getattr(self, attname).strftime(BASE_TIME_FORMATE)
                    except:
                        d[attr] = '00:00'
                elif t == models.CommaSeparatedIntegerField:
                    if isinstance(getattr(self, attname), (str, unicode)):
                        d[attr] = json.loads(getattr(self, attname, '[]'))
                    else:
                        d[attr] = getattr(self, attname)
                else:
                    d[attr] = getattr(self, attname)
        d['s_id'] = d.get('id')
        return d

class NSUserManager(UserManager):

    def create_superuser(self, username, password, email='xx@xx.xx', **extra_fields):
        print username
        print password
    #

class NSUser(AbstractBaseUser, JSONBaseMixin):
    """
    用户表
    by: 李艳军 at:2017-07-19
    """

    name = models.CharField(max_length=30, unique=True, null=True, blank=True)
    realname = models.CharField(max_length=30, null=True, blank=True, verbose_name=u'真实姓名')
    create_time = models.DateTimeField(default=timezone.now, verbose_name=u'创建时间')
    manager_status = models.IntegerField(default=0, db_index=True, null=True)

    objects = NSUserManager()


    USERNAME_FIELD = 'name'
    REQUIRED_FIELDS = []


class TestCrontab(models.Model, JSONBaseMixin):
    """
    脚本测试
    by: 李艳军 at:2016-06-27
    """
    version = models.CharField(max_length=100, verbose_name=u'版本号')
    create_time = models.DateTimeField(default=timezone.now, verbose_name=u'创建时间')


    def toJSON(self):
        d = super(TestCrontab, self).toJSON()

        return d


    def save(self, *args, **kwargs):
        super(TestCrontab, self).save(*args, **kwargs)

